use std::{io::{self, Write}, path::Path};

use git2::{Cred, IndexAddOption, PushOptions, RemoteCallbacks, Repository, Signature};
 
#[test]
fn test() {

    
    //克隆
    // let repo = match Repository::clone(url, "/path/to/a/repo") {
    //     Ok(repo) => repo,
    //     Err(e) => panic!("failed to clone: {}", e),
    // };


}

pub fn init(url: &str, path: &str) {
    let repo = match Repository::open(path) {
        Ok(repo) => {
            repo
        },
        Err(_) => {
            println!("本地没有仓库!{}****, {}", url, path);
            let repo = match Repository::clone(url, path) {
                Ok(repo) => repo,
                Err(e) => panic!("failed to clone: {}", e),
            };
            repo
        },
    };
}



pub fn push(url: &str, path: &str, file_path: &str, username: String, email: String, login_name: String, password: String) {
    let repo = match Repository::open(path) {
        Ok(repo) => {
            repo
        },
        Err(_) => {
            println!("本地没有仓库!");
            let repo = match Repository::clone(url, path) {
                Ok(repo) => repo,
                Err(e) => panic!("failed to clone: {}", e),
            };
            repo
        },
    };
    
    let mut index = match repo.index() {
        Ok(index) => {
            println!("成功获取index!");
            index
        },
        Err(e) => panic!("获取index失败: {}", e),
    };

    println!("文件地址:{}", file_path);

    match index.add_path(Path::new(file_path)) {
        Ok(_) => {
            println!("成功!");
            match index.write() {
                Ok(_) => {
                    println!("成功!");
                },
                Err(e) => panic!("写入失败: {}", e),
            }
        },
        Err(e) => panic!("加入失败: {}", e),
    }
    

        // 创建一个新的提交
        let oid = index.write_tree().unwrap();
        let signature = Signature::now( &username, &email).unwrap();
        let tree = repo.find_tree(oid).unwrap();
    
        let parent_commit = match repo.head() {
            Ok(head) => Some(repo.find_commit(head.target().unwrap()).unwrap()),
            Err(_) => None,
        };
    
        let commit_oid = match parent_commit {
            Some(parent) => repo.commit(
                Some("HEAD"), &signature, &signature, "Add new_file.txt",
                &tree, &[&parent]
            ).unwrap(),
            None => repo.commit(
                Some("HEAD"), &signature, &signature, "Initial commit",
                &tree, &[]
            ).unwrap(),
        };

        // 设置推送选项和回调
        let mut push_options = PushOptions::new();
        let mut callbacks = RemoteCallbacks::new();
        callbacks.credentials(|_, _, _| {
            Cred::userpass_plaintext(&login_name, &password)
        });
        push_options.remote_callbacks(callbacks);
    
        // 将更改推送到远程仓库
        let mut remote = repo.find_remote("origin").or_else(|_| repo.remote("origin", url)).unwrap();

        match remote.push(&["refs/heads/master:refs/heads/master"], Some(&mut push_options)) {
            Ok(_) => {
                println!("成功!");
            },
            Err(e) => panic!("推送失败: {}", e),
        }

}

pub fn push_all(url: &str, path: &str, username: String, email: String, login_name: String, password: String) {
    let repo = match Repository::open(path) {
        Ok(repo) => {
            repo
        },
        Err(_) => {
            println!("本地没有仓库!");
            let repo = match Repository::clone(url, path) {
                Ok(repo) => repo,
                Err(e) => panic!("failed to clone: {}", e),
            };
            repo
        },
    };
    
    let mut index = match repo.index() {
        Ok(index) => {
            index
        },
        Err(e) => panic!("获取index失败: {}", e),
    };



    match index.add_all(["*"].iter(), IndexAddOption::DEFAULT, None) {
        Ok(_) => {
            println!("成功!");
            match index.write() {
                Ok(_) => {
                    println!("成功!");
                },
                Err(e) => panic!("写入失败: {}", e),
            }
        },
        Err(e) => panic!("加入失败: {}", e),
    }
    

        // 创建一个新的提交
        let oid = index.write_tree().unwrap();
        let signature = Signature::now( &username, &email).unwrap();
        let tree = repo.find_tree(oid).unwrap();
    
        let parent_commit = match repo.head() {
            Ok(head) => Some(repo.find_commit(head.target().unwrap()).unwrap()),
            Err(_) => None,
        };
    
        let commit_oid = match parent_commit {
            Some(parent) => repo.commit(
                Some("HEAD"), &signature, &signature, "Add new_file.txt",
                &tree, &[&parent]
            ).unwrap(),
            None => repo.commit(
                Some("HEAD"), &signature, &signature, "Initial commit",
                &tree, &[]
            ).unwrap(),
        };

        // 设置推送选项和回调
        let mut push_options = PushOptions::new();
        let mut callbacks = RemoteCallbacks::new();
        callbacks.credentials(|_, _, _| {
            Cred::userpass_plaintext(&login_name, &password)
        });
        push_options.remote_callbacks(callbacks);
    
        // 将更改推送到远程仓库
        let mut remote = repo.find_remote("origin").or_else(|_| repo.remote("origin", url)).unwrap();

        match remote.push(&["refs/heads/master:refs/heads/master"], Some(&mut push_options)) {
            Ok(_) => {
                println!("成功!");
            },
            Err(e) => panic!("推送失败: {}", e),
        }

}



pub fn pull(url: &str, path: &str, remote_name: &str, remote_branch: &str) {
    let repo = match Repository::open(path) {
        Ok(repo) => {
            repo
        },
        Err(_) => {
            println!("本地没有仓库!{}****, {}", url, path);
            let repo = match Repository::clone(url, path) {
                Ok(repo) => repo,
                Err(e) => panic!("failed to clone: {}", e),
            };
            repo
        },
    };

    match repo.find_remote(remote_name) {
        Ok(mut remote) => {
            match do_fetch(&repo, &[remote_branch], &mut remote) {
                Ok(fetch_commit) => {
                    let _ = do_merge(&repo, &remote_branch, fetch_commit);
                },
                Err(_) => {
                    println!("查找fetch!")
                },
            }
        },
        Err(_) => {
            println!("发现远程失败!")
        },
    };
}


pub fn del_file(url: &str, path: &str, file_path: &str, username: String, email: String, login_name: String, password: String) {
    let repo = match Repository::open(path) {
        Ok(repo) => {
            repo
        },
        Err(_) => {
            println!("本地没有仓库!");
            let repo = match Repository::clone(url, path) {
                Ok(repo) => repo,
                Err(e) => panic!("failed to clone: {}", e),
            };
            repo
        },
    };
    
    let mut index = match repo.index() {
        Ok(index) => {
            println!("成功获取index!");
            index
        },
        Err(e) => panic!("获取index失败: {}", e),
    };

    println!("文件地址:{}", file_path);

    match index.remove_path(Path::new(file_path)) {
        Ok(_) => {
            println!("成功!");
            match index.write() {
                Ok(_) => {
                    println!("成功!");
                },
                Err(e) => panic!("写入失败: {}", e),
            }
        },
        Err(e) => panic!("加入失败: {}", e),
    }
    

        // 创建一个新的提交
        let oid = index.write_tree().unwrap();
        let signature = Signature::now( &username, &email).unwrap();
        let tree = repo.find_tree(oid).unwrap();
    
        let parent_commit = match repo.head() {
            Ok(head) => Some(repo.find_commit(head.target().unwrap()).unwrap()),
            Err(_) => None,
        };
    
        let commit_oid = match parent_commit {
            Some(parent) => repo.commit(
                Some("HEAD"), &signature, &signature, "Add new_file.txt",
                &tree, &[&parent]
            ).unwrap(),
            None => repo.commit(
                Some("HEAD"), &signature, &signature, "Initial commit",
                &tree, &[]
            ).unwrap(),
        };

        // 设置推送选项和回调
        let mut push_options = PushOptions::new();
        let mut callbacks = RemoteCallbacks::new();
        callbacks.credentials(|_, _, _| {
            Cred::userpass_plaintext(&login_name, &password)
        });
        push_options.remote_callbacks(callbacks);
    
        // 将更改推送到远程仓库
        let mut remote = repo.find_remote("origin").or_else(|_| repo.remote("origin", url)).unwrap();

        match remote.push(&["refs/heads/master:refs/heads/master"], Some(&mut push_options)) {
            Ok(_) => {
                println!("成功!");
            },
            Err(e) => panic!("推送失败: {}", e),
        }

}


fn do_fetch<'a>(
    repo: &'a git2::Repository,
    refs: &[&str],
    remote: &'a mut git2::Remote,
) -> Result<git2::AnnotatedCommit<'a>, git2::Error> {
    let mut cb = git2::RemoteCallbacks::new();

    // Print out our transfer progress.
    cb.transfer_progress(|stats| {
        if stats.received_objects() == stats.total_objects() {
            print!(
                "Resolving deltas {}/{}\r",
                stats.indexed_deltas(),
                stats.total_deltas()
            );
        } else if stats.total_objects() > 0 {
            print!(
                "Received {}/{} objects ({}) in {} bytes\r",
                stats.received_objects(),
                stats.total_objects(),
                stats.indexed_objects(),
                stats.received_bytes()
            );
        }
        io::stdout().flush().unwrap();
        true
    });

    let mut fo = git2::FetchOptions::new();
    fo.remote_callbacks(cb);
    // Always fetch all tags.
    // Perform a download and also update tips
    fo.download_tags(git2::AutotagOption::All);
    println!("Fetching {} for repo", remote.name().unwrap());
    remote.fetch(refs, Some(&mut fo), None)?;

    // If there are local objects (we got a thin pack), then tell the user
    // how many objects we saved from having to cross the network.
    let stats = remote.stats();
    if stats.local_objects() > 0 {
        println!(
            "\rReceived {}/{} objects in {} bytes (used {} local \
             objects)",
            stats.indexed_objects(),
            stats.total_objects(),
            stats.received_bytes(),
            stats.local_objects()
        );
    } else {
        println!(
            "\rReceived {}/{} objects in {} bytes",
            stats.indexed_objects(),
            stats.total_objects(),
            stats.received_bytes()
        );
    }

    let fetch_head = repo.find_reference("FETCH_HEAD")?;
    Ok(repo.reference_to_annotated_commit(&fetch_head)?)
}




fn do_merge<'a>(
    repo: &'a Repository,
    remote_branch: &str,
    fetch_commit: git2::AnnotatedCommit<'a>,
) -> Result<(), git2::Error> {
    // 1. do a merge analysis
    let analysis = repo.merge_analysis(&[&fetch_commit])?;

    // 2. Do the appropriate merge
    if analysis.0.is_fast_forward() {
        println!("Doing a fast forward");
        // do a fast forward
        let refname = format!("refs/heads/{}", remote_branch);
        match repo.find_reference(&refname) {
            Ok(mut r) => {
                fast_forward(repo, &mut r, &fetch_commit)?;
            }
            Err(_) => {
                // The branch doesn't exist so just set the reference to the
                // commit directly. Usually this is because you are pulling
                // into an empty repository.
                repo.reference(
                    &refname,
                    fetch_commit.id(),
                    true,
                    &format!("Setting {} to {}", remote_branch, fetch_commit.id()),
                )?;
                repo.set_head(&refname)?;
                repo.checkout_head(Some(
                    git2::build::CheckoutBuilder::default()
                        .allow_conflicts(true)
                        .conflict_style_merge(true)
                        .force(),
                ))?;
            }
        };
    } else if analysis.0.is_normal() {
        // do a normal merge
        let head_commit = repo.reference_to_annotated_commit(&repo.head()?)?;
        normal_merge(&repo, &head_commit, &fetch_commit)?;
    } else {
        println!("Nothing to do...");
    }
    Ok(())
}


fn normal_merge(
    repo: &Repository,
    local: &git2::AnnotatedCommit,
    remote: &git2::AnnotatedCommit,
) -> Result<(), git2::Error> {
    let local_tree = repo.find_commit(local.id())?.tree()?;
    let remote_tree = repo.find_commit(remote.id())?.tree()?;
    let ancestor = repo
        .find_commit(repo.merge_base(local.id(), remote.id())?)?
        .tree()?;
    let mut idx = repo.merge_trees(&ancestor, &local_tree, &remote_tree, None)?;

    if idx.has_conflicts() {
        println!("Merge conflicts detected...");
        repo.checkout_index(Some(&mut idx), None)?;
        return Ok(());
    }
    let result_tree = repo.find_tree(idx.write_tree_to(repo)?)?;
    // now create the merge commit
    let msg = format!("Merge: {} into {}", remote.id(), local.id());
    let sig = repo.signature()?;
    let local_commit = repo.find_commit(local.id())?;
    let remote_commit = repo.find_commit(remote.id())?;
    // Do our merge commit and set current branch head to that commit.
    let _merge_commit = repo.commit(
        Some("HEAD"),
        &sig,
        &sig,
        &msg,
        &result_tree,
        &[&local_commit, &remote_commit],
    )?;
    // Set working tree to match head.
    repo.checkout_head(None)?;
    Ok(())
}


fn fast_forward(
    repo: &Repository,
    lb: &mut git2::Reference,
    rc: &git2::AnnotatedCommit,
) -> Result<(), git2::Error> {
    let name = match lb.name() {
        Some(s) => s.to_string(),
        None => String::from_utf8_lossy(lb.name_bytes()).to_string(),
    };
    let msg = format!("Fast-Forward: Setting {} to id: {}", name, rc.id());
    println!("{}", msg);
    lb.set_target(rc.id(), &msg)?;
    repo.set_head(&name)?;
    repo.checkout_head(Some(
        git2::build::CheckoutBuilder::default()
            // For some reason the force is required to make the working directory actually get updated
            // I suspect we should be adding some logic to handle dirty working directory states
            // but this is just an example so maybe not.
            .force(),
    ))?;
    Ok(())
}